from flask import current_app
from apscheduler.events import EVENT_JOB_EXECUTED, EVENT_JOB_ADDED
from task_app.extensions import scheduler
from extensions import db
from task_app.models import JobPlan


def update_next_run_time(event):
    """ 更新数据库next_run_time """
    scheduler_job = scheduler.get_job(event.job_id)
    plan = JobPlan.query.filter(JobPlan.task_id == event.job_id).first()
    if plan:
        plan.next_run_time = scheduler_job.next_run_time
        db.session.commit()
        current_app.logger.info("【更新任务[%s] 的next_run_time：[%s]】" % (plan.task_id, plan.next_run_time))


def job_added(event):
    """Job added event."""
    with scheduler.app.app_context():
        update_next_run_time(event)


def job_executed(event):
    """Job executed event."""
    with scheduler.app.app_context():
        # 更新数据库next_run_time
        update_next_run_time(event)
        # 插入job_event 记录


scheduler.add_listener(job_executed, EVENT_JOB_EXECUTED)
scheduler.add_listener(job_added, EVENT_JOB_ADDED)
